import { createRouter, createWebHistory } from 'vue-router'
import { useLoadingStore } from './store/useLoadingStore'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/pages/HomePage.vue'),
  },
  {
    path: '/categories',
    name: 'Categories',
    component: () => import('@/pages/CategoriesPage.vue'),
  },
  {
    path: '/search',
    name: 'SearchResults',
    component: () => import('@/pages/SearchResultsPage.vue'),
  },
  {
    path: '/ai-create',
    name: 'AiCreate',
    component: () => import('@/pages/AiCreatePage.vue'),
  },
  {
    path: '/upload-movie',
    name: 'UploadMovie',
    component: () => import('@/pages/UploadMoviePage.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/upload',
    name: 'Upload',
    component: () => import('@/pages/UploadMoviePage.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/edit-movie/:id',
    name: 'EditMovie',
    component: () => import('@/pages/EditMoviePage.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/movie/:id',
    name: 'MovieDetail',
    component: () => import('@/pages/MovieDetailPage.vue'),
  },
  {
    path: '/movie/:id/play',
    name: 'MoviePlay',
    component: () => import('@/pages/MoviePlayPage.vue'),
  },
  {
    path: '/user/:id',
    name: 'UserProfile',
    component: () => import('@/pages/UserProfilePage.vue'),
  },
  {
    path: '/settings',
    name: 'Settings',
    component: () => import('@/pages/SettingsPage.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/auth/callback',
    name: 'AuthCallback',
    component: () => import('@/pages/AuthCallbackPage.vue'),
  },
  {
    path: '/auth-demo',
    name: 'AuthDemo',
    component: () => import('@/pages/AuthDemoPage.vue'),
  },
  {
    path: '/test-components',
    name: 'TestComponents',
    component: () => import('@/pages/TestComponentsPage.vue'),
  },
  {
    path: '/toast-test',
    name: 'ToastTest',
    component: () => import('@/pages/ToastTest.vue'),
  },
  {
    path: '/messages',
    name: 'Messages',
    component: () => import('@/pages/MessagesPage.vue'),
  },
  {
    path: '/admin',
    name: 'AdminPanel',
    component: () => import('@/pages/AdminPanelPage.vue'),
    meta: { requiresAuth: true, requiresModerator: true },
  },
  {
    path: '/tag-management',
    name: 'TagManagement',
    component: () => import('@/pages/TagManagementPage.vue'),
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(_to, _from, savedPosition) {
    // 如果有保存的位置（比如用户点击了浏览器的后退按钮），则恢复到该位置
    if (savedPosition) {
      return savedPosition
    }

    // 对于所有路由变化，都滚动到顶部
    // 注意：由于使用了MainLayout，滚动是在main元素内进行的
    return new Promise((resolve) => {
      setTimeout(() => {
        const mainContent = document.querySelector('main')
        if (mainContent) {
          mainContent.scrollTop = 0
        }
        resolve({ top: 0 })
      }, 100)
    })
  },
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const loadingStore = useLoadingStore()

  // 只在非首页或从其他页面跳转到首页时显示加载动画
  if (to.path !== '/' || from.path !== '/') {
    loadingStore.startLoading()
  }

  // 清理电影表单状态（如果从编辑页面切换到其他页面）
  if (from.path.startsWith('/edit-movie/') && to.path !== from.path) {
    try {
      const { useMovieStore } = await import('./store/useMovieStore')
      const movieStore = useMovieStore()
      movieStore.clearFormOnRouteChange()
    } catch (error) {
      console.warn('清理电影表单状态失败:', error)
    }
  }

  // 基于路由元信息的权限控制
  const requiresAuth = to.matched.some(record => record.meta && (record.meta as any).requiresAuth)
  const requiresModerator = to.matched.some(
    record => record.meta && (record.meta as any).requiresModerator,
  )

  if (requiresAuth || requiresModerator) {
    const { useUserStore } = await import('./store/useUserStore')
    const userStore = useUserStore()

    // 确保已获取当前用户
    if (userStore.loading) {
      await userStore.getCurrentUser()
    }

    if (!userStore.isAuthenticated) {
      next('/')
      return
    }

    if (requiresModerator) {
      try {
        const hasPermission = await userStore.isModerator()
        if (!hasPermission) {
          next('/')
          return
        }
      } catch (error) {
        console.error('权限检查失败:', error)
        next('/')
        return
      }
    }
  }

  next()
})

router.afterEach((to, from) => {
  const loadingStore = useLoadingStore()

  // 只在非首页或从其他页面跳转到首页时隐藏加载动画
  if (to.path !== '/' || from.path !== '/') {
    loadingStore.finishLoading()
  }
})

export default router
